package com.david.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author David
 * @version V1.0
 * @Package com.david.rabbitmq
 * @date 2021/7/17 0:24
 */
public class HelloworldConsumer {
    private final static String QUEUE_NAME="david_hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        //连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //配置连接信息
        factory.setHost("192.168.219.203");
        factory.setVirtualHost("/");
        factory.setUsername("root");
        factory.setPassword("123456");
        factory.setPort(5672);

        // 获取连接
        Connection connection = factory.newConnection();
        // 从连接获取通道
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println("消费者等待消息......");
        // 消息的推送回调函数
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("消费者消费消息：" + message + "");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag-> System.out.println("consumerTag = " + consumerTag));
    }
}
